<?php

namespace app\general\controller;


use think\Controller;
use think\Db;
use think\Request;
use think\cache\driver\Redis;

class HandleArticle extends Controller
{
    protected $redis;

    protected $rand_array;

    protected $today;

    function __construct(Request $request = null)
    {
        parent::__construct($request);
        //$this->redis = new Redis();
        $this->rand_array = [
            1 => [50, 500],
            2 => [500, 1500],
            3 => [500, 1500],
            4 => [500, 1500],
            5 => [200, 800],
            6 => [200, 800],
            7 => [200, 800],
            8 => [10, 200],
            9 => [10, 200],
            10 => [10, 200],
        ];
        $this->today = strtotime(date("Y-m-d 24:00:00", time()));
    }

    /**
     * 每天定时修改10天内的文章的阅读量
     */
    public function handle()
    {
        $id = $this->recordTimers(13);
        // 走定时器，不存在会少加一天，所以这里没有进行判断 1588559600
        // 1.查询10天内发布的文章：是否包含今天
        $where['create_time'] = ['between', [strtotime("-10 day"), $this->today]];
        $list = model('sq_article')->where($where)->field('id,create_time,show_read_num')->select();
        if ($list) {
            $data = [];
            // 进行修改阅读量
            foreach ($list as $value) {
                // 2.进行文章的时间判断。A文章发布了一天，则加0-20的随机值
                $day = $this->timeDiff($this->today, $value['create_time']);
                // 3.获取随机数配置值
                $rand_num_arr = $this->getRandNum($day,1,'show_read_num');
                if($rand_num_arr){
                    $read_num = $rand_num_arr[0]["show_read_num"];
                    // 5.构建数据
                    $data[] = ['id' => $value['id'], 'show_read_num' => $value['show_read_num'] + $read_num];
                }
            }
            // 6.批量修改
            $res = model('sq_article')->saveAll($data);
            if ($res) {
                return success('', '批量更新成功');
            } else {
                return error('批量更新失败');
            }
        }
        $this->updateTimerType($id, 'success');
    }

    /**
     * 随机数
     * @return mixed
     */
    public function getRandNum($day, $limit = 1, $field = 'num')
    {
        $array = [];
        // 天数必须大于等于1天，并且要小于等于10天，10天以后就不管
        if ($day >= 1 && $day <= 10) {
            $begin = $this->rand_array[$day][0];
            $end = $this->rand_array[$day][1];
            $rand_array = range($begin, $end);
            shuffle($rand_array);
            $rand_array = array_slice($rand_array, 0, $limit);
            foreach ($rand_array as $key => $val) {
                $array[][$field] = $val;
            }
        }
        return $array;
    }

    /**
     * 计算数组值得和
     * @param $array
     * @param $day
     * @return float|int
     */
    public function arraySum($array, $day)
    {
        return array_sum(array_chunk($array, $array[$day])[0]);
    }

    /**
     * 计算时间差
     * @param $begin_time
     * @param $end_time
     * @return mixed
     */
    public function timeDiff($begin_time, $end_time)
    {
        if ($begin_time < $end_time) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        //计算天数
        $timediff = $endtime - $starttime;
        $days = intval($timediff / 86400);
        //计算小时数
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);
        return $res['day'];
    }


    //记录定时器调用时间
    public function recordTimers($type)
    {
        $data = [
            'type' => $type,
            'create_time' => time(),
            'status' => 0
        ];
        return db('sq_record_timer')->insertGetId($data);
    }

    public function updateTimerType($id, $remark = '')
    {
        db('sq_record_timer')->where('id', $id)->update(['status' => 1, 'remark' => $remark]);
    }

}









